package com.bawei.module_home.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bawei.module_home.R
import com.bawei.module_home.home.model.entity.VideoEntity
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners

/*
使用 DiffUtil 进行高效刷新：
在 setData() 中使用 DiffUtil 计算差异，只刷新变化的 item
需要确保 VideoEntity 有唯一标识符（如 id）和正确的 equals() 方法
精准控制刷新范围：
addData() 使用 notifyItemRangeInserted
updateItem() 使用 notifyItemChanged
removeItem() 使用 notifyItemRemoved
 */

class VideoAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    private val data = arrayListOf<VideoEntity>()
    private var isLoading = false

    // 添加点击事件接口
    var onItemClickListener: ((VideoEntity) -> Unit)? = null

    // 定义两种视图类型
    companion object {
        private const val TYPE_ITEM = 0  // 普通item类型
        private const val TYPE_LOADING = 1  // 加载更多item类型
    }

    // 修改1: 使用 DiffUtil 进行高效局部刷新
    fun setData(newData: List<VideoEntity>) {
        val diffResult = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
            override fun getOldListSize() = data.size
            override fun getNewListSize() = newData.size
            override fun areItemsTheSame(oldPos: Int, newPos: Int): Boolean {
                return data[oldPos].id == newData[newPos].id // 假设 VideoEntity 有唯一ID
            }
            override fun areContentsTheSame(oldPos: Int, newPos: Int): Boolean {
                return data[oldPos] == newData[newPos]
            }
        })
        data.clear()
        data.addAll(newData)
        diffResult.dispatchUpdatesTo(this) // 局部刷新
    }

    // 修改2: 添加数据时使用局部刷新
    fun addData(newData: List<VideoEntity>) {
        val startPosition = data.size
        data.addAll(newData)
        notifyItemRangeInserted(startPosition, newData.size) // 只刷新新增部分
    }

    // 修改3: 单独更新某个item
    fun updateItem(position: Int, newItem: VideoEntity) {
        if (position in 0 until data.size) {
            data[position] = newItem
            notifyItemChanged(position) // 只刷新指定位置
        }
    }

    // 修改4: 删除item时局部刷新
    fun removeItem(position: Int) {
        if (position in 0 until data.size) {
            data.removeAt(position)
            notifyItemRemoved(position) // 只刷新删除位置
        }
    }
//在 setLoading() 中添加状态变化检查，避免不必要的刷新
    //只刷新加载项所在的位置
    fun setLoading(isLoading: Boolean) {
        if (this.isLoading != isLoading) {
            val position = data.size
            this.isLoading = isLoading
            if (isLoading) {
                notifyItemInserted(position) // 只添加加载项
            } else {
                notifyItemRemoved(position) // 只移除加载项
            }
        }
    }


    override fun getItemViewType(position: Int): Int {
        return if (position < data.size) TYPE_ITEM else TYPE_LOADING
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_ITEM -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_video, parent, false)
                VideoViewHolder(view)
            }

            else -> {
                val view = LayoutInflater.from(parent.context)
                    .inflate(R.layout.item_loading, parent, false)
                LoadingViewHolder(view)
            }
        }
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is VideoViewHolder -> {
                bindVideoItem(holder, position)
            }

            is LoadingViewHolder -> {
                holder.bind(isLoading)  // 更新加载状态
            }
        }
    }
    // 修改5: 提取绑定逻辑，方便单独刷新时复用
    private fun bindVideoItem(holder: VideoViewHolder, position: Int) {
        val item = data[position]
        holder.name.text = item.name
        holder.introduction.text = item.title
        holder.comment_tv.text = "${item.commentnum}"

        Glide.with(holder.itemView.context)
            .load(item.videomainimag)
            .transform(CenterCrop(), RoundedCorners(20))
            .into(holder.img)

        Glide.with(holder.itemView.context)
            .load(item.avatar_url)
            .transform(CircleCrop())
            .into(holder.header)

        // 添加点击事件
        holder.itemView.setOnClickListener {
            onItemClickListener?.invoke(item)
        }

        // 三个点弹出菜单
        val moreView = holder.itemView.findViewById<ImageView>(R.id.more)
        moreView.setOnClickListener { v ->
            val popup = android.widget.PopupMenu(v.context, v)
            popup.menu.add("更多")
            popup.menu.add("进入详情")
            popup.setOnMenuItemClickListener { menuItem ->
                when (menuItem.title) {
                    "更多" -> {
                        // TODO: 实现更多操作
                        android.widget.Toast.makeText(v.context, "暂无更多", android.widget.Toast.LENGTH_SHORT).show()
                        true
                    }
                    "进入详情" -> {
                        // 跳转到详情页，使用ARouter
                        val json = com.google.gson.Gson().toJson(item)
                        com.alibaba.android.arouter.launcher.ARouter.getInstance()
                            .build("/detail/DetailActivity")
                            .withString("detail", json)
                            .navigation()
                         true
                    }
                    else -> false
                }
            }
            popup.show()
        }

        // 评论图标跳转到详情页面（使用ARouter）
        val commentIcon = holder.itemView.findViewById<ImageView>(R.id.comment_icon)
        commentIcon.setOnClickListener { v ->
            // 跳转到详情页，使用ARouter
            val json = com.google.gson.Gson().toJson(item)
            com.alibaba.android.arouter.launcher.ARouter.getInstance()
                .build("/detail/DetailActivity")
                .withString("detail", json)
                .navigation()
        }
    }


    override fun getItemCount() = data.size + if (isLoading) 1 else 0


    inner class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
       //将属性声明为 val 避免重复查找
       val img: ImageView
        val header: ImageView
        val name: TextView
        val introduction: TextView
        val comment_tv: TextView
        val more: ImageView
        val comment_icon: ImageView

        init {
            img = view.findViewById(R.id.img)
            header = view.findViewById(R.id.header)
            name = view.findViewById(R.id.name)
            introduction = view.findViewById(R.id.introduction)
            comment_tv = view.findViewById(R.id.comment_text)
            more = view.findViewById(R.id.more)
            comment_icon = view.findViewById(R.id.comment_icon)
        }
    }

    inner class LoadingViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val progressBar: ProgressBar = view.findViewById(R.id.progressBar)
        val loadingText: TextView = view.findViewById(R.id.loadingText)

        init {
            // 设置默认状态
            loadingText.text = "正在拼命加载中..."
            progressBar.visibility = View.VISIBLE
        }

        fun bind(isLoading: Boolean) {
            // 如果需要动态更新可以调用这个方法
            progressBar.visibility = if (isLoading) View.VISIBLE else View.GONE
            loadingText.text = if (isLoading) "正在拼命加载中..." else "加载完成"
        }
    }
}